﻿using dz.loger.core;

using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.Ship;
using dz.util.core;
using Dz.WorkerService.Utils;
using System.Data;

namespace Dz.WorkerService.Service
{
    public class OfflineSipService : BaseShip
    {
        public OfflineSipService(string processId):base(processId)
        {
            docType = "出货-线下订单";
        }
        protected async override Task<DataTable> GetProcessData()
        {
            string sql = @"select id,pdate,xtype,shopcode,deptcode,org,wh,tradeno,tradeid,parent,goodsno,sellcount,sellamt,orgamt,platcode,
                        shipdate,isfit,flag,isadjust,cust,price from dz_jky_SO where flag=3 and sellcount >0 and xtype=1";

            DataTable dt = await sqlUtils.Fill(sql);

            return dt;
        }
        protected override async Task Process()
        {
            List<string> doc = dt
                     .AsEnumerable()
                     .Select(r => r.Field<string>("tradeno"))
                     .Distinct()
                     .ToList();

            foreach (string s in doc)
            {
                await Import(s);
            }

        }

        private async Task Import(string docNo)
        {
            DataRow[] rows = dt.Select($"tradeno='{docNo}'");

            string cust = rows[0]["cust"].ToString();
            string org = rows[0]["org"].ToString();
            string tradeid = rows[0]["tradeid"].ToString();
            string extWhere = $" and tradeid = '{tradeid}'";

            if (!CustUtils.Instance.IsExists(cust, org))
            {
                LogUtil.Instance.Debug($"{docNo} 客户 {cust} 在U9中不存在，跳过");
                await UpdateDataState(2, extWhere);
                return;
            }

            DzShip ship = new DzShip();

            ship.DocumentType = "SM4";
            ship.OrderBy = cust;
            ship.Org = rows[0]["org"].ToString();
            ship.TC = currencys[ship.Org];
            ship.AC = ship.TC;
            ship.BusinessDate = Convert.ToDateTime(rows[0]["shipdate"]);
            DescFlexField headFlex = new DescFlexField();
            headFlex.PubDescSeg8 = rows[0]["tradeno"].ToString();
            headFlex.PrivateDescSeg10 = "经销";
            ship.DescFlexField = headFlex;
            ship.IsPriceIncludeTax = true;


            ship.SaleDept = rows[0]["deptcode"].ToString();
            ship.Org = org;
            string taxSchedule = TaxScheduleUtils.Instance.GetTaxSchedule(ship.SaleDept, org);
            if (taxSchedule.Length > 0) ship.TaxSchedule = taxSchedule;


            List<DzShipLine> lines = new List<DzShipLine>();
            foreach (DataRow row in rows) 
            {
                DzShipLine line = new DzShipLine();

                string inv = row["goodsno"].ToString();

                if (!InvUtils.Instance.IsExists(inv, org))
                {
                    LogUtil.Instance.Debug($"{docNo} 存货{inv} 在U9中不存在，跳过");
                    continue;
                }
                line.DonationType = -1;
                line.ItemInfo = inv;
                line.ShipQtyInvAmount = Convert.ToDecimal(row["sellcount"]);
                line.WH = row["wh"].ToString();
                line.OrderPrice = Convert.ToDecimal(row["price"]);
                line.OrderPriceTC = line.OrderPrice;
                line.FinallyPrice = line.OrderPrice;
                line.FinallyPriceTC = line.OrderPrice;

                DescFlexField bodyFlex = new DescFlexField();

                bodyFlex.PubDescSeg8 = ship.DescFlexField.PubDescSeg8;
                bodyFlex.PrivateDescSeg8 = "经销";
                bodyFlex.PrivateDescSeg3 = "导入";
                line.DescFlexField = bodyFlex;
                LogUtil.Instance.Debug($"OrderPriceTC = {line.OrderPriceTC}" );

                if (line.OrderPriceTC == 0) line.DonationType = 0;



                lines.Add(line);
            }

            if (lines.Count == 0)
            {
                await UpdateDataState(2, extWhere);
                return;
            } 

            ship.ShipLines = lines;

            //U9CResult result = await U9Utils.Post(controller, "AddAndAudit", JsonUtil.Serialize(ship));

            U9CResult result = await U9Utils.Post(controller, "Add", JsonUtil.Serialize(ship));

            await UpdateSyncLog(result, extWhere);
            
        }
    }
}
